import React from 'react';
import { H, TT, DviceWidth, Img, DviceHeight } from '@/components';
import { Animated, DeviceEventEmitter, LayoutChangeEvent } from 'react-native';
import { R } from '@/assets';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

export interface TGlobalToastProps {
  message: string;
  success: number; //1成功 2失败 3warn
}

export function GlobalToast() {
  const [toast, setToast] = React.useState<TGlobalToastProps>();
  const [base] = React.useState(() => new Animated.Value(0));
  const [height, setHeight] = React.useState(DviceHeight);
  const insets = useSafeAreaInsets();
  const timer = React.useRef<NodeJS.Timeout>();
  React.useEffect(() => {
    const sub = DeviceEventEmitter.addListener(
      ShowGlobalToastCmd,
      (result: TGlobalToastProps) => {
        onShow(result);
      }
    );
    return () => sub.remove();
  }, []);

  React.useEffect(() => {
    if (toast) {
      timer.current = setTimeout(() => {
        onHide();
      }, 5000);
    } else {
      clearTimeout(timer.current);
    }
  }, [toast]);

  const onShow = (result: TGlobalToastProps) => {
    setToast(result);
    Animated.timing(base, {
      toValue: 1,
      duration: 250,
      useNativeDriver: true,
    }).start();
  };

  const onHide = () => {
    Animated.timing(base, {
      toValue: 0,
      duration: 250,
      useNativeDriver: true,
    }).start(() => {
      setToast(undefined);
    });
  };

  const getImg = () => {
    if (toast?.success === 1) {
      return R.common.success();
    } else if (toast?.success == 3) {
      return R.common.warn();
    }
    return R.common.closeIcon();
  };

  const onLayout = (e: LayoutChangeEvent) => {
    setHeight(e.nativeEvent.layout.height);
  };

  const tran = React.useMemo(() => {
    return {
      ty: base.interpolate({
        inputRange: [0, 1],
        outputRange: [height + insets.bottom + 25, 0],
      }),
    };
  }, [height, base]);

  if (!toast) return null;
  return (
    <H
      nf
      br="10"
      bg="#AFB3FF"
      w={DviceWidth - 32}
      h={55}
      ai="c"
      pos={[, 16, insets.bottom + 25, 16]}
      ph={12}
      onPress={onHide}
      onLayout={onLayout}
      ty={tran.ty}
    >
      <Img wh={24} src={getImg()} />
      <TT nol="0" fs={18} fw="400" ml={17}>
        {toast?.message}
      </TT>
    </H>
  );
}

export const ShowGlobalToastCmd = 'global-toast-show';
